// pages/ucenter/addressEdit/addressEdit.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var check = require('../../../utils/check.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // infoList:{
    //   name: null,
    //   mobile: null,
    //   addr: null,
    //   isDefault: null
    // },
    address: {
      id: 0,
      provinceId: 0,
      cityId: 0,
      areaId: 0,
      address: '',
      name: '',
      mobile: '',
      isDefault: 0,
      provinceName: '',
      cityName: '',
      areaName: '',
      isfirst: 0,
      version: ''
    },
    addressId: 0,
    openSelectRegion: false,
    selectRegionList: [{
        id: 0,
        name: '省份',
        pid: 1,
        type: 1
      },
      {
        id: 0,
        name: '城市',
        pid: 1,
        type: 2
      },
      {
        id: 0,
        name: '区县',
        pid: 1,
        type: 3
      }
    ],
    regionType: 1,
    regionList: [],
    selectRegionDone: false
  },
  //删除地址
  deleteAddress(event) {
    console.log(event.target)
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要删除地址？',
      success: function(res) {
        if (res.confirm) {
          let addressId = event.target.dataset.addressId;
          util.request(api.AddressDelete, {
            id: addressId
          }, 'POST').then(function(res) {
            if (res.errno === 0) {
              that.getAddressList();
              wx.removeStorage({
                key: 'addressId',
                success: function(res) {},
              })
            }
          });
          console.log('用户点击确定')
        }
      }
    })
    return false;

  },
  // 获取地址信息
  getInfo: function() {
    let updateAddress = wx.getStorageSync('updateAddress')
    console.log(updateAddress)
    let info = this.data.address
    info.provinceName = updateAddress.province
    info.cityName = updateAddress.city
    info.areaName = updateAddress.area
    info.isDefault = updateAddress.isDefault
    info.name = updateAddress.name
    info.mobile = updateAddress.mobile
    info.address = updateAddress.addr
    info.id = updateAddress.id
    info.provinceId = updateAddress.provinceId
    info.cityId = updateAddress.cityId
    info.areaId = updateAddress.districtId
    info.version = updateAddress.version
    this.setData({
      address: info
    })
    console.log(this.data.address)
  },
  //获取修改信息的方法
  getUpdateInfo(data, tip) {
    let addr = this.data.address
    console.log(tip + ':' + data)
    switch (tip) {
      case 'name':
        addr.name = data
        break;
      case 'mobile':
        addr.mobile = data
        break;
      case 'addr':
        addr.address = data
        break;
      case 'isDefault':
        addr.isDefault = data
        break;
    }
    this.setData({
      address: addr
    })
  },
  //修改省市区
  changeAddress: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      addressArray: e.detail.value
    })
  },
  //获取联系人
  getName: function(e) {
    this.getUpdateInfo(e.detail.value, 'name')
  },
  //获取手机号
  getMobile: function(e) {
    this.getUpdateInfo(e.detail.value, 'mobile')
  },
  //获取详细地址
  getDetailAddress: function(e) {
    this.getUpdateInfo(e.detail.value, 'addr')
  },
  // 获取输入地址
  bindinputAddress(event) {
    let address = this.data.address;
    address.address = event.detail.value;
    this.setData({
      address: address
    });
  },
  //获取默认
  switchChange: function(e) {
    this.getUpdateInfo(e.detail.value, 'isDefault')
  },
  //修改地址
  updateAddress: function() {
    let address = this.data.address;

    if (address.name == '') {
      util.showErrorToast('请输入姓名');

      return false;
    }

    if (address.mobile == '') {
      util.showErrorToast('请输入手机号码');
      return false;
    }

    // if (address.areaId == 0) {
    //   util.showErrorToast('请输入省市区');
    //   return false;
    // }

    if (address.address == '') {
      util.showErrorToast('请输入详细地址');
      return false;
    }

    if (!check.isValidPhone(address.mobile)) {
      util.showErrorToast('手机号不正确');
      return false;
    }
    
    util.request(api.AddressSave, {
      id: address.id,
      name: address.name,
      mobile: address.mobile,
      provinceId: address.provinceId,
      cityId: address.cityId,
      areaId: address.areaId,
      address: address.address,
      isDefault: address.isDefault,
      provinceName: address.provinceName,
      cityName: address.cityName,
      countyName: address.areaName,
      version: address.version
    }, 'POST').then(function(e) {
      if (e.errno == 0) {
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        })
      }
    })
  },
  // 设置确定的状态
  setRegionDoneStatus() {
    let that = this;
    let doneStatus = that.data.selectRegionList.every(item => {
      return item.id != 0;
    });
    console.log(doneStatus)
    that.setData({
      selectRegionDone: doneStatus
    })

  },
  // 显示地址框
  chooseRegion() {
    let that = this;
    this.setData({
      openSelectRegion: !this.data.openSelectRegion
    });

    //设置区域选择数据
    let address = this.data.address;
    console.log(address)
    if (address.provinceId > 0 && address.cityId > 0 && address.areaId > 0) {
      let selectRegionList = this.data.selectRegionList;
      selectRegionList[0].id = address.provinceId;
      selectRegionList[0].name = address.provinceName;
      selectRegionList[0].pid = 0;

      selectRegionList[1].id = address.cityId;
      selectRegionList[1].name = address.cityName;
      selectRegionList[1].pid = address.provinceId;

      selectRegionList[2].id = address.areaId;
      selectRegionList[2].name = address.areaName;
      selectRegionList[2].pid = address.cityId;
      this.setData({
        selectRegionList: selectRegionList,
        regionType: 3
      });

      this.getRegionList(address.cityId);
    } else {
      this.setData({
        selectRegionList: [{
            id: 0,
            name: '省份',
            pid: 0,
            type: 1
          },
          {
            id: 0,
            name: '城市',
            pid: 0,
            type: 2
          },
          {
            id: 0,
            name: '区县',
            pid: 0,
            type: 3
          }
        ],
        regionType: 1
      })
      console.log(this.data.selectRegionList)
      this.getRegionList(0);
    }

    this.setRegionDoneStatus();

  },
  // 设置省市区的选中状态
  selectRegionType(event) {
    let that = this;
    let regionTypeIndex = event.target.dataset.regionTypeIndex;
    let selectRegionList = that.data.selectRegionList;
    //判断是否可点击
    if (regionTypeIndex + 1 == this.data.regionType || (regionTypeIndex - 1 >= 0 && selectRegionList[regionTypeIndex - 1].id <= 0)) {
      return false;
    }

    this.setData({
      regionType: regionTypeIndex + 1
    })

    let selectRegionItem = selectRegionList[regionTypeIndex];

    this.getRegionList(selectRegionItem.pid);

    this.setRegionDoneStatus();

  },
  // 选择省市区项
  selectRegion(event) {
    let that = this;
    let regionIndex = event.target.dataset.regionIndex;
    let regionItem = this.data.regionList[regionIndex];
    console.log(regionItem)
    let regionType = regionItem.type;
    let selectRegionList = this.data.selectRegionList;
    selectRegionList[regionType - 1] = regionItem;


    if (regionType != 3) {
      this.setData({
        selectRegionList: selectRegionList,
        regionType: regionType + 1
      })
      this.getRegionList(regionItem.id);
    } else {
      this.setData({
        selectRegionList: selectRegionList
      })
    }
    //重置下级区域为空
    selectRegionList.map((item, index) => {
      if (index > regionType - 1) {
        item.id = 0;
        item.name = index == 1 ? '城市' : '区县';
        item.pid = 0;
      }
      return item;
    });

    this.setData({
      selectRegionList: selectRegionList
    })

    that.setData({
      regionList: that.data.regionList.map(item => {

        //标记已选择的
        if (that.data.regionType == item.type && that.data.selectRegionList[that.data.regionType - 1].id == item.id) {
          item.selected = true;
        } else {
          item.selected = false;
        }

        return item;
      })
    });
    console.log(this.data.regionList)
    this.setRegionDoneStatus();

  },
  // 确定选择的省市区
  doneSelectRegion() {
    if (this.data.selectRegionDone === false) {
      return false;
    }

    let address = this.data.address;
    let selectRegionList = this.data.selectRegionList;
    address.provinceId = selectRegionList[0].id;
    address.cityId = selectRegionList[1].id;
    address.areaId = selectRegionList[2].id;
    address.provinceName = selectRegionList[0].name;
    address.cityName = selectRegionList[1].name;
    address.areaName = selectRegionList[2].name;

    this.setData({
      address: address,
      openSelectRegion: false
    });

  },
  // 获得省市区
  getRegionList(regionId) {
    let that = this;
    let regionType = that.data.regionType;
    util.request(api.RegionList, {
      pid: regionId
    }).then(function(res) {
      if (res.errno === 0) {
        that.setData({
          regionList: res.data.map(item => {

            //标记已选择的
            if (regionType == item.type && that.data.selectRegionList[regionType - 1].id == item.id) {
              item.selected = true;
            } else {
              item.selected = false;
            }

            return item;
          })
        });
      }
    });
  },
  cancelSelectRegion() {
    this.setData({
      openSelectRegion: false,
      regionType: this.data.regionDoneStatus ? 3 : 1
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})